package com.mit.wx.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 2018/10/23 Create by 郭文梁
 * QrCodeUtil
 * 二维码工具类
 *
 * @author 郭文梁
 * @date 2018/10/23
 */
public class QrCodeUtil {
    private static final String DEFAULT_CHARSET = "utf-8";
    private static final ErrorCorrectionLevel DEFAULT_ERROR_CORRECTION_LEVEL = ErrorCorrectionLevel.M;
    private static final int DEFAULT_MARGIN = 2;
    private static final String DEFAULT_FORMAT = "png";

    /**
     * 编码二维码
     *
     * @param str    内容
     * @param width  宽度
     * @param height 高度
     * @return 字节数组
     */
    public static byte[] encode(String str, int width, int height) {
        return encode(str, width, height, DEFAULT_CHARSET, DEFAULT_ERROR_CORRECTION_LEVEL, DEFAULT_MARGIN);
    }

    /**
     * 编码二维码
     *
     * @param str                  内容
     * @param width                宽度
     * @param height               高度
     * @param charset              编码格式
     * @param errorCorrectionLevel 容错等级
     * @param margin               边距
     * @return 字节数组
     */
    public static byte[] encode(String str, int width, int height, String charset, ErrorCorrectionLevel errorCorrectionLevel, Integer margin) {
        Map<EncodeHintType, Object> conf = new HashMap<>(3);
        conf.put(EncodeHintType.CHARACTER_SET, charset);
        conf.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);
        conf.put(EncodeHintType.MARGIN, margin);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, width, height, conf);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, DEFAULT_FORMAT, bos);
            bos.close();
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
